/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.deployment.servlet;

import br.com.deployment.dao.AddressDAO;
import br.com.deployment.daoImpl.AddressDAOImpl;
import br.com.deployment.daoImpl.AnexoDAOImpl;
import br.com.deployment.daoImpl.CategoryDAOImpl;
import br.com.deployment.daoImpl.IssuesDAOImpl;
import br.com.deployment.daoImpl.NotaryOfficeDAOImpl;
import br.com.deployment.daoImpl.OptionsDAOImpl;
import br.com.deployment.daoImpl.QuestionnaireDAOImpl;
import br.com.deployment.daoImpl.QuestionnaireResponseDAOImpl;
import br.com.deployment.daoImpl.ResponseDAOImpl;
import br.com.deployment.entities.*;
import br.com.menulayout.util.Base64;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;

/**
 *
 * @author roniere
 */
@WebServlet(name = "receiverUtilMobileServlet", urlPatterns = "/receiverUtilMobileServlet/*")
public class ReceiverUtilMobileServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    @EJB
    QuestionnaireDAOImpl questionnaireDAO;
    @EJB
    QuestionnaireResponseDAOImpl questionnaireResponseDAO;
    @EJB
    ResponseDAOImpl responseDAO;
    @EJB
    CategoryDAOImpl categoryDAO;
    @EJB
    IssuesDAOImpl issuesDAO;
    @EJB
    OptionsDAOImpl optionsDAO;
    @EJB
    AnexoDAOImpl anexoService;
    @EJB
    NotaryOfficeDAOImpl notaryOfficeService;
    @EJB
    AddressDAOImpl addressService;
    private final String ID_EXECUTOR = "id_executor";
    private final String MOD_GET_LAZY = "mod_get_lazy";
    private final String ID_QUESTIONNAIRE = "id_questionnaire";

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String idExecutor = request.getParameter(ID_EXECUTOR);
        String modSearch = request.getParameter(MOD_GET_LAZY);
        String idQuestionnaire = request.getParameter(ID_QUESTIONNAIRE);

        if (modSearch != null && !Boolean.parseBoolean(modSearch)) {
            getQuestionnaireResponseJSON(idQuestionnaire, response);
        } else if (modSearch != null) {
            System.err.println(modSearch);
            getQuestionnaireResponseJSONLazy(idExecutor, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        processRequest(req, resp);
    }

    public void getQuestionnaireResponseJSONLazy(String id, HttpServletResponse response) throws IOException {
        Gson gson = new Gson();
        response.setContentType("charset=UTF-8");
        PrintWriter out = response.getWriter();
        Executor exce = new Executor();
        exce.setId(Long.valueOf(id));
        List<QuestionnaireResponse> queResp = questionnaireResponseDAO.findAll();//QuestionnaireResponseExecutor(exce);//ndQuestionnaireResponseExecutorPendent(exce);

        StringBuffer json = new StringBuffer();

        for (QuestionnaireResponse questionnaireResponse : queResp) {
            Questionnaire questi = questionnaireDAO.find(questionnaireResponse.getQuestionnaire().getId());
            questi.setCategorys(null);
            questionnaireResponse.setQuestionnaire(questi);
            questionnaireResponse.setResponse(null);
            questionnaireResponse.setAnexo(null);
            questionnaireResponse.getExecutor().setGroups(null);

        }
        
//        System.err.println("IMPORT---->>" + queResp);
        out.write(gson.toJson(queResp));
    }

    public void getQuestionnaireResponseJSON(String id, HttpServletResponse response) throws IOException {

        if (id == null) {
            return;
        }

        Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();

        List<QuestionnaireResponse> queResp = new ArrayList<QuestionnaireResponse>();//questionnaireResponseDAO.findQuestionnaireResponseExecutor(exce);//ndQuestionnaireResponseExecutorPendent(exce);

        queResp.add(questionnaireResponseDAO.find(Long.valueOf(id)));

        for (QuestionnaireResponse questionnaireResponse : queResp) {

            Questionnaire questi = questionnaireDAO.find(questionnaireResponse.getQuestionnaire().getId());


            List<Category> category = categoryDAO.findCategoryQuestionnaire(questi);

            for (Category category1 : category) {
                List<Issues> findIssuesType = issuesDAO.findIssuesType(category1, questi);

                for (Issues issues : findIssuesType) {
                    issues.setOptions(optionsDAO.findOptionsType(issues));
                    issues.setCategory(null);
                    issues.setQuestionnaire(null);
//                    issues.setTypeIssues(null);
                }

                category1.setIssueses(findIssuesType);

            }
            questi.setCategorys(category);

            questionnaireResponse.setQuestionnaire(questi);
            questionnaireResponse.setResponse(null);
            questionnaireResponse.setAnexo(null);
            questionnaireResponse.getExecutor().setGroups(null);
            System.err.println(questionnaireResponse.getNotaryOffice());
        }

        response.setContentType("charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(gson.toJson(queResp));
    }

    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestData = processRequest(request);
        Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
        JSONObject jSONObject;

        System.err.println("JSON" + requestData);
        try {
            jSONObject = new JSONObject(requestData);

            if (jSONObject.get("mod") != null) {

                Anexo anexoJson = gson.fromJson(requestData, Anexo.class);


                Anexo anexo = anexoService.findUUID(anexoJson.getCod(), anexoJson.getUUID());
                anexo.setContent(anexoJson.getContent());
                anexo.setContentByte(Base64.decode(anexoJson.getContent()));

                System.err.println("UPDATE" + anexo.getId());
                anexoService.update(anexo);

                return;
            }
        } catch (JSONException ex) {
            Logger.getLogger(ReceiverUtilMobileServlet.class.getName()).log(Level.SEVERE, null, ex);
            
        

        QuestionnaireResponse questionnarie = gson.fromJson(requestData, QuestionnaireResponse.class);
        
        System.err.println("COD: " + questionnarie.getCod());
        QuestionnaireResponse questionnarieLocal = questionnaireResponseDAO.find(questionnarie.getCod());
        
        questionnarieLocal.setQuestionnaire(questionnaireDAO.find(questionnarieLocal.getQuestionnaire().getId()));

        NotaryOffice notaryOffice = questionnarie.getNotaryOffice();
        NotaryOffice saveNotaryOffice = notaryOfficeService.find(notaryOffice.getCod());
        
        saveNotaryOffice.setNome(notaryOffice.getNome());
	saveNotaryOffice.setTitular(notaryOffice.getTitular());
	saveNotaryOffice.setDenominationOffice(notaryOffice.getDenominationOffice());
	saveNotaryOffice.setNatureOffice(notaryOffice.getNatureOffice());
	saveNotaryOffice.setEmail(notaryOffice.getEmail());
        saveNotaryOffice.setCpf(notaryOffice.getCpf());
	saveNotaryOffice.setDatePossesion(notaryOffice.getDatePossesion());
	saveNotaryOffice.setCnpj(notaryOffice.getCnpj());
        
        Address address = notaryOffice.getAddress();
        
        
        Address addressSave = addressService.find(address.getCod());
        
        addressSave.setStreet(address.getStreet());
        addressSave.setDistrict(address.getDistrict());
        addressSave.setNum(address.getNum());
        addressSave.setPhone(address.getPhone());
        addressSave.setCellular(address.getCellular());
        addressSave.setCep(address.getCep());
        addressSave.setComplement(address.getComplement());
        
        
        saveNotaryOffice.setAddress(addressSave);
                    
        if(saveNotaryOffice != null){
            notaryOfficeService.update(saveNotaryOffice);
        }
        
        List<Response> listResp = new ArrayList<Response>();
        for (Response rsp : questionnarie.getResponse()) {
            rsp.setId(null);

            rsp.setIssues(issuesDAO.find(rsp.getIssues().getCod()));

            List<Options> lst = new ArrayList<Options>();
            List<String> idsArray;


            for (Anexo ann : rsp.getAnexo()) {
                ann.setId(null);
//                System.err.println("UUID:" + ann.getUUID());
            }
            

            if (!rsp.getIdOptions().isEmpty() && rsp.getIdOptions().length() > 0) {
                idsArray = Arrays.asList(rsp.getIdOptions().split("-"));
                for (String string : idsArray) {
                    if (string != "") {
                        Options op = optionsDAO.find(Long.parseLong(string));
                        lst.add(op);
                    }

                }
            }



            rsp.setOptionses(lst);
//            responseDAO.save(rsp);
            System.err.println("Resposta:" + rsp);
            listResp.add(rsp);
        }

        
        
        questionnarieLocal.setResponse(listResp);
        questionnarieLocal.setConclusion(questionnarie.getConclusion());
        questionnarieLocal.setScore(questionnarie.getScore());
        questionnarieLocal.setAnexo(questionnarie.getAnexo());
        System.err.println(questionnarieLocal);

        questionnaireResponseDAO.update(questionnarieLocal);


        PrintWriter out = response.getWriter();

        //      questionnaireDAO.find(x.getCod());

        out.write("{ teste }");
        }
    }

    private String processRequest(HttpServletRequest request) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                jb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jb.toString();

    }
}
